
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SPCFMedicineInformer.DocumentTypes;
using Vega.USiteBuilder;
using umbraco.MacroEngines;
using umbraco.cms.businesslogic.web;
using umbraco.BusinessLogic;
using SPCFMedicineInformer.Constants;
using umbraco.NodeFactory;
using SPCFMedicineInformer.Helpers;
using System.Text;
using System.Web.Configuration;
using umbraco;

namespace SPCFMedicineInformer.Masterpages
{
    public partial class Admin_EditMedicine : TemplateBase<AdminContentPage>
    {
        #region declaration
        int id;
        User UmbracoUser = User.GetUser(0);
        string orig_med_name = string.Empty;
        public IEnumerable<Symptom> SymptomsListing { get; set; }
        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            int tempInt;
            id = Request.QueryString["id"] != null ? int.TryParse(Request.QueryString["id"].ToString(),out tempInt) ? tempInt : 1 : 0;
            bool isNew = Request.QueryString["n"] != null ? Request.QueryString["n"].ToString() == "1" ? true : false : false;
            BindSymptomsList();
            btnDelete.Visible = id > 0 ? true : false;
            if (!IsPostBack)
            {
                PopulateDropdowns();
                if (id > 0)
                {
                    var node = new Node(id);
                    
                    var medicineItem = node != null && node.NodeTypeAlias == "MedicineItem" ? ContentHelper.GetByNodeId<DocumentTypes.MedicineItem>(id) : null;
                    if (medicineItem != null)
                    {

                        string strCategoryId = !string.IsNullOrEmpty(medicineItem.CategoryId) ? medicineItem.CategoryId.ToString() : "0";
                        string strGenericId = !string.IsNullOrEmpty(medicineItem.GenericId) ? medicineItem.GenericId.ToString() : "0";
                        ddlCategory.SelectedValue = strCategoryId;
                        ddlGenericName.SelectedValue = strGenericId;
                        hiddenOriginalCategoryId.Value = strCategoryId;
                        hiddenOriginalGenericNameId.Value = strGenericId;

                        
                        orig_med_name = !string.IsNullOrEmpty(medicineItem.MedicineNameMT) ? medicineItem.MedicineNameMT : medicineItem.Name;
                        txtMedicineName.Text = orig_med_name;
                        txtIndication.Text = medicineItem.Indication;
                        txtDosages.Text = medicineItem.Dosages;
                        txtContradiction.Text = !string.IsNullOrEmpty(medicineItem.ContradictionMT) ? medicineItem.ContradictionMT : medicineItem.Contradiction;
                        txtSpecialPrecautions.Text =  medicineItem.SpecialPrecautions;
                        txtAdverseReactions.Text = !string.IsNullOrEmpty(medicineItem.AdverseReactionsMT) ? medicineItem.AdverseReactionsMT : medicineItem.AdverseReactions;
                        txtPresentationPackaging.Text = !string.IsNullOrEmpty(medicineItem.PregnancySafetyMT) ? medicineItem.PregnancySafetyMT : medicineItem.Presentation_Packaging;
                        txtPregnancySafety.Text = !string.IsNullOrEmpty(medicineItem.PregnancySafetyMT) ? medicineItem.PregnancySafetyMT : medicineItem.PregnancySafety;
                        txtDrugInteraction.Text = medicineItem.DrugInteraction;
                        hiddenSymptomList.Value = medicineItem.Symptoms;
                        slideImage.ImageUrl = medicineItem.ImageUrl;
                        txtAdministration.Text = medicineItem.Administration;
                        ShowExistingImage(!string.IsNullOrEmpty(medicineItem.ImageUrl) ? true : false);

                        rdoAge.Text = medicineItem.PrescriptionAgeType;
                        txtFromAge.Text = rdoAge.Text == "Specific Age" ? medicineItem.PrescriptionFromAge.ToString() : "";
                        txtToAge.Text =  rdoAge.Text == "Specific Age" ? medicineItem.PrescriptionToAge.ToString() : "";

                        if (isNew)//display the message save text if new medicine
                            FormHelper.ShowMessage(MessageType.Done, "Medicine Succesfully Saved!", MsgLiteral);
                        ShowContent(true);
                    }
                    else
                    {
                        ShowContent(false);
                        FormHelper.ShowMessage(MessageType.Error, "Medicine does not exist!", MsgLiteral);
                        editHolder.Visible = false;
                        id = 0;
                    }
                }
                else
                {
                    
                    ShowExistingImage(false);
                    btnAddNewMedicine.Visible = false;
                }
            }
            else
            {
                var genericNameList = NodeLocator.GetNodesOfExactType<MedicineGenericName>().OrderBy(node => node.Name).ToList();
                AddGenericClass(genericNameList);
            }
            
        }
        void ShowContent(bool b)
        {
            plcContent.Visible = b;
            plcError.Visible = !b;
        }
        void BindSymptomsList()
        {
            SymptomsListing = NodeLocator.GetNodesOfExactType<Symptom>();            
        }
        void AddGenericClass(List<MedicineGenericName> list)
        {
            int i = 1;
            foreach (var item in list)
            {
                ddlGenericName.Items[i].Attributes.Add("class", item.ParentId.ToString());
                i++;
            }
        }
        void PopulateDropdowns()
        {
            int maxChar = 35;
            var categoryList = NodeLocator.GetNodesOfExactType<MedicineCategory>().OrderBy(node => node.Name).ToList();
            ddlCategory.Items.Clear();
            ddlCategory.DataSource = categoryList;
            ddlCategory.DataTextField = "Name";
            ddlCategory.DataValueField = "Id";
            ddlCategory.DataBind();
            ddlCategory.Items.Insert(0, new ListItem("Choose...", "0"));

            var genericNameList = NodeLocator.GetNodesOfExactType<MedicineGenericName>().OrderBy(node=>node.Name).ToList();; 
            ddlGenericName.Items.Clear();
            ddlGenericName.DataSource = genericNameList;
            ddlGenericName.DataTextField = "Name";
            ddlGenericName.DataValueField = "Id";
            ddlGenericName.DataBind();
            ddlGenericName.Items.Insert(0, new ListItem("", "0"));
            AddGenericClass(genericNameList);
        }
        int AddNew()
        {
            DocumentType UmbracoDocType = DocumentType.GetByAlias("MedicineItem");
            int genId = int.Parse(ddlGenericName.SelectedValue);
            if (genId > 0)
            {
                Document d = Document.MakeNew(StringUtils.TruncateIfLonger(txtMedicineName.Text, 250), UmbracoDocType, User.GetUser(0), genId);
                TransferDetailsToUmbraco(d);
                return d.Id;
            }
            return 0;
        }
        void Update()
        {
            if (id > 0)
            {
                int tempInt;
                int genId = int.Parse(ddlGenericName.SelectedValue);
                int orig_gen_id = int.TryParse(hiddenOriginalGenericNameId.Value,out tempInt) ? tempInt : 0;
                Node n = new Node(id);
                if (n != null)
                {
                    var d = new Document(id);
                    if (d != null)
                    {
                        TransferDetailsToUmbraco(d);
                        if (genId != orig_gen_id)
                            UmbracoNodeHelper.MoveNode(genId, d.Id);
                    }
                }
                
            }
            
        }
        void TransferDetailsToUmbraco(Document MedicineNode)
        {
            if (plcNewImage.Visible)
            {
                MedicineNode.getProperty(UmbracoPropertyName.IMAGE_URL).Value = UploadImage(MedicineNode.Id);
            }
            MedicineNode.Text = StringUtils.TruncateIfLonger(txtMedicineName.Text,250);
            MedicineNode.getProperty(UmbracoPropertyName.MEDICINE_NAME_MT).Value = txtMedicineName.Text;
            MedicineNode.getProperty(UmbracoPropertyName.CATEGORY_ID).Value = ddlCategory.SelectedValue;
            MedicineNode.getProperty(UmbracoPropertyName.GENERIC_ID).Value = ddlGenericName.SelectedValue;
            MedicineNode.getProperty(UmbracoPropertyName.CATEGORY_NAME).Value = GetName(ddlCategory.SelectedValue);
            MedicineNode.getProperty(UmbracoPropertyName.GENERIC_NAME).Value = GetName(ddlGenericName.SelectedValue);
            MedicineNode.getProperty(UmbracoPropertyName.INDICATION).Value = txtIndication.Text;
            MedicineNode.getProperty(UmbracoPropertyName.DOSAGES).Value = txtDosages.Text;
            MedicineNode.getProperty(UmbracoPropertyName.CONTRADICTION_MT).Value = txtContradiction.Text;
            MedicineNode.getProperty(UmbracoPropertyName.SPECIAL_PRECAUTIONS).Value = txtSpecialPrecautions.Text;
            MedicineNode.getProperty(UmbracoPropertyName.ADVERSE_REACTION_MT).Value = txtAdverseReactions.Text;
            MedicineNode.getProperty(UmbracoPropertyName.PRESENTATION_PACKAGING_MT).Value = txtPresentationPackaging.Text;
            MedicineNode.getProperty(UmbracoPropertyName.PREGNANCY_SAFETY_MT).Value = txtPregnancySafety.Text;
            MedicineNode.getProperty(UmbracoPropertyName.DRUG_INTERACTION).Value = txtDrugInteraction.Text;
            MedicineNode.getProperty(UmbracoPropertyName.ADMINISTRATION).Value = txtAdministration.Text;
            MedicineNode.getProperty(UmbracoPropertyName.SYMPTOMS).Value = hiddenSymptomList.Value;

            MedicineNode.getProperty(UmbracoPropertyName.PREGNANCY_SAFETY).Value = "";
            MedicineNode.getProperty(UmbracoPropertyName.PRESENTATION_PACKAGING).Value = "";
            MedicineNode.getProperty(UmbracoPropertyName.PREGNANCY_SAFETY).Value = "";
            MedicineNode.getProperty(UmbracoPropertyName.CONTRADICTION).Value = "";
            MedicineNode.getProperty(UmbracoPropertyName.MEDICINE_NAME).Value = "";
            MedicineNode.getProperty(UmbracoPropertyName.ADVERSE_REACTION).Value = "";

            string fromAge = string.Empty, toAge = string.Empty;
            if (rdoAge.SelectedValue == "Specific Age")
            {
                fromAge = txtFromAge.Text;
                toAge = txtToAge.Text;
            }
            MedicineNode.getProperty(UmbracoPropertyName.FROM_AGE).Value = fromAge;
            MedicineNode.getProperty(UmbracoPropertyName.TO_AGE).Value = toAge;
            MedicineNode.getProperty(UmbracoPropertyName.AGE_TYPE).Value = rdoAge.Text;
            MedicineNode.Publish(UmbracoUser);
            umbraco.library.UpdateDocumentCache(MedicineNode.Id);

        }
        string GetName(string strId)
        {
            int tempInt;
            int id = int.TryParse(strId,out tempInt) ? tempInt : 0;
            Node n = new Node(id);
            if (n != null)
            {
                return n.Name;
            }
            return "";
        }
        protected void btnSaveMedicine_Click(object sender, EventArgs e)
        {
            if (IsValidate())
            {
                if (id > 0)
                {
                    Update();
                    FormHelper.ShowMessage(MessageType.Done, "Medicine Item Succesfully Saved!", MsgLiteral);
                }
                else // add new medicinie
                {
                    id = AddNew();

                    if (id > 0)
                        Response.Redirect("/admin/utilities/medicine-entry.aspx?id=" + id.ToString() + "&n=1");
                }
            }
            
            
        }
        bool IsValidate()
        {
            bool result = true;
            int tempInt;
            int genId = int.Parse(ddlGenericName.SelectedValue);
            int orig_gen_id = int.TryParse(hiddenOriginalGenericNameId.Value, out tempInt) ? tempInt : 0;
            var sb = new StringBuilder();
            var msgFormat = "<p class=\"{0}\">{1}</p>";

            if (ddlGenericName.SelectedIndex <= 0)
            {
                sb.AppendLine(string.Format(msgFormat, "msg warning", "Generic Name is required!"));
                result = false;
            }
            if (ddlCategory.SelectedIndex <= 0)
            {
                sb.AppendLine(string.Format(msgFormat, "msg warning", "Category is required!"));
                result = false;
            }
            if (string.IsNullOrWhiteSpace(txtMedicineName.Text))
            {
                sb.AppendLine(string.Format(msgFormat, "msg warning", "Medicine Name is required!"));
                result = false;
            }
            else if (genId != orig_gen_id && genId > 0)
            {
                if (ContentHelper.GetByNodeId<MedicineGenericName>(genId).GetChildren<MedicineItem>().Where(a => a.Name.ToLower() == txtMedicineName.Text.ToLower()).Count() > 0)
                {
                    result = false;
                    sb.AppendLine(string.Format(msgFormat, "msg error", "Medicine Name exist!"));
                } 
            }

            if (rdoAge.SelectedValue == "Specific Age")
            {
                int fromAge = int.TryParse(txtFromAge.Text, out tempInt) ? tempInt : -1;
                int toAge = int.TryParse(txtToAge.Text, out tempInt) ? tempInt : -1;
                if (fromAge == -1 || toAge == -1)
                {
                    result = false;
                    sb.AppendFormat(msgFormat, "msg warning", "Please enter a valid age.");
                }
                else if (fromAge > toAge)
                {
                    result = false;
                    sb.AppendFormat(msgFormat, "msg warning", "\"From Age\" must not greater than \"To Age\".");
                }
            }
            

            


            if (!result)
            {
                MsgLiteral.Visible = true;
                MsgLiteral.Text = sb.ToString();
            }
            return result;
        }
        protected void btnAddMedicine_Click(object sender, EventArgs e)
        {
            Response.Redirect("/admin/utilities/medicine-entry.aspx");
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("/admin/utilities/medicine-listings.aspx");
        }       
        protected void lbUploadNew_Click(object sender, EventArgs e)
        {
            ShowExistingImage(false, true);
        }
        protected void lbCanceUpload_Click(object sender, EventArgs e)
        {
            ShowExistingImage(true);
        }
        void ShowExistingImage(bool value, bool cancel = false)
        {
            plcExistingImage.Visible = value;
            lbCancelUpload.Visible = cancel;
            plcNewImage.Visible = !value;
        }
        string UploadImage(int id)
        {
            if (FileUpload1.HasFile)
            {
                string strFile = WebConfigurationManager.AppSettings["ImagePath"] + id.ToString() + "-" + FileUpload1.FileName;
                string filepath = Server.MapPath(strFile);
                FileUpload1.SaveAs(filepath);
                ShowExistingImage(true);
                slideImage.ImageUrl = strFile;
                return strFile.Remove(0, 1);
            }
            return "";
        }
        void Delete(int id)
        {
            if (id > 0)
            {
                Document doc = new Document(id);
                if (doc.Published)
                {
                    doc.UnPublish();
                    library.UnPublishSingleNode(doc.Id);
                }
                doc.delete();
                Response.Redirect("/admin/utilities/medicine-listings.aspx");
            }
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            Delete(id);
        }

    }
}

